package com.loveto.service;

import java.io.UnsupportedEncodingException;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.loveto.common.JsonUtils;
import com.loveto.constant.LovetoConstant;

public class MessageNoticeActivity extends BaseActivity implements
View.OnClickListener{
	
	private static final int TOURNAMENT_STATUS_ING = 1;
	// 사용하는 변수들
	private ProgressDialog progressDialog;
	private LinearLayout contentMain;
	private String memberid;
	private String gender;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.loveto_message_notice);
		
		((RelativeLayout)findViewById(R.id.btn_goto_back)).setOnClickListener(this);
		contentMain = (LinearLayout)findViewById(R.id.content_main);
		
		SharedPreferences pref = getSharedPreferences("userInfo", Activity.MODE_PRIVATE);
		memberid = pref.getString("memberid", "");
		gender = pref.getString("gender", "");

		progressDialog = new ProgressDialog(MessageNoticeActivity.this);
		progressDialog.setMessage("정보를 불러오고있습니다.");
		progressDialog.show();
		
		if (isNetworkAvailableAndNotice()) {
			setMessageNoticeList();
		}
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_goto_back:
			finish();
			break;
		case R.id.click_area:
			//영역에 적혀있는 텍스트을 읽고 다음 엑티비티에 전달함.
			TextView tournamentIDTextView = (TextView)v.findViewById(R.id.tournamentID);
			TextView messageTypeTextView = (TextView)v.findViewById(R.id.messageType);
			
			String tournamentID = tournamentIDTextView.getText().toString();
			String messageType = messageTypeTextView.getText().toString();
			Intent intent;
			
			switch(Integer.parseInt(messageType)) {
				case 1:
				case 4:
				case 5:
					//info
					intent = new Intent(MessageNoticeActivity.this, InfoTournamentActivity.class);
					intent.putExtra("tournamentID", tournamentID);
					startActivity(intent);
					break;
				case 2:
				case 6:
					//slide
					intent = new Intent(MessageNoticeActivity.this, SlideshowWinnerIntermidRoundActivity.class);
					intent.putExtra("tournamentID", tournamentID);
					startActivity(intent);
					break;
				case 3:
					//select
					//이미 선택이 완료된 토너먼트 인경우 select 화면으로 넘어가면 안됨. alert 창 뿌려줌.
					if (checkTournamentEnd(tournamentID)) {
						showSimpleAlert("이미 종료 된 토너먼트입니다.");
					} else {
						intent = new Intent(MessageNoticeActivity.this, SelectWinnerIntermidRoundActivity.class);
						intent.putExtra("tournamentID", tournamentID);
						startActivity(intent);
					}
					break;
			}
		}
	}
	
	private boolean checkTournamentEnd(String tournamentID) {
		// 원격에서 읽어온 데이터로 JSON 객체 생성
		try {
			String jsonText = JsonUtils.getStringFromUrl(LovetoConstant.TOURNAMENT_CHECK_END_URL + "?tournamentid=" + tournamentID);
			Log.d("tag", jsonText);
			JSONObject noticeObject = new JSONObject(jsonText);
			int tournamentStatus = noticeObject.getInt("tournamentStatus");
			
			Log.d("tag", "tournamentStatus : " + tournamentStatus);
			
			if (tournamentStatus != TOURNAMENT_STATUS_ING) {
				return false;
			} else {
				return true;
			}
		} catch (Exception e) {
			Log.e("tag", e.getMessage());
			e.printStackTrace();
			return true;
		}
	}
	
	private void setMessageNoticeList() {
		new AsyncTask<Void, RelativeLayout, String>() {
			
			// 이곳에 포함된 code는 AsyncTask가 execute 되자 마자 UI 스레드에서 실행됨.
			// 작업 시작을 UI에 표현하거나
			// background 작업을 위한 ProgressBar를 보여 주는 등의 코드를 작성.
			@Override
			protected void onPreExecute() {
				progressDialog.setMessage("정보를 불러오고있습니다.");
				progressDialog.show();
				Log.d("tag", "Background 작업 시작 ");
				super.onPreExecute();
			}

			// UI 스레드에서 AsynchTask객체.execute(...) 명령으로 실행되는 callback
			@Override
			protected String doInBackground(Void... params) {
				try {
					String jsonText = JsonUtils
							.getStringFromUrl(LovetoConstant.SYSTEM_MESSAGE_LIST_URL + "?memberid=" + memberid);
					 Log.d("tag", jsonText);
					// 원격에서 읽어온 데이터로 JSON 객체 생성
					try {
						JSONArray jsonArray = new JSONArray(jsonText);
						if (jsonArray!=null) {
							int jsonArrayLen = jsonArray.length();
							Log.d("tag","길이는?" + jsonArrayLen);
	
							for (int i = 0; i < jsonArrayLen; i++) {
								JSONObject object = jsonArray.getJSONObject(i);
								
								
								RelativeLayout messageNoticeLayout = makeRelativeLayout(object);
								publishProgress(messageNoticeLayout);
							}
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
				
				return "true";
			}
			
			@Override
			protected void onProgressUpdate(RelativeLayout... progress) {
				contentMain.addView(progress[0]);
			}

			@Override
			protected void onPostExecute(String result) {
				// 프로그레스 다이얼로그 끄기
				progressDialog.dismiss();
				Log.d("tag", "화면 노출 ");
			}

			// AsyncTask.cancel(boolean) 메소드가 true 인자로
			// 실행되면 호출되는 콜백.
			// background 작업이 취소될때 꼭 해야될 작업은 여기에 구현.
			@Override
			protected void onCancelled() {
				super.onCancelled();
			}
		}.execute();
	}
	
	private RelativeLayout makeRelativeLayout(JSONObject object) throws JSONException {
		RelativeLayout messageNoticeLayout;
		
		String tournamentid = object.getString("tournamentid");
		String tournamentMakerMemberid = object.getString("tournament_maker_memberid");
		String messageType = object.getString("message_type");
		String regdate = object.getString("regdate");
		String readYn = object.getString("read_yn");
		
		if ("M".equals(gender)) {
			messageNoticeLayout = (RelativeLayout)getLayoutInflater().inflate(R.layout.loveto_message_notice_man, null);
		} else {
			messageNoticeLayout = (RelativeLayout)getLayoutInflater().inflate(R.layout.loveto_message_notice_woman, null);
		}
		
		TextView memberidTextView = (TextView)messageNoticeLayout.findViewById(R.id.memberid);
		TextView noticeMessageTextView = (TextView)messageNoticeLayout.findViewById(R.id.notice_message);
		TextView noticeMessageRegdateTextView = (TextView)messageNoticeLayout.findViewById(R.id.notice_message_regdate);
		TextView tournamentIDTextView = (TextView)messageNoticeLayout.findViewById(R.id.tournamentID);
		TextView messageTypeTextView = (TextView)messageNoticeLayout.findViewById(R.id.messageType);
		
		messageTypeTextView.setText(messageType);
		memberidTextView.setText("! " + tournamentMakerMemberid);
		
		if("N".equals(readYn)) {
			noticeMessageTextView.setTextColor(getResources().getColor(R.color.softYellow));
			noticeMessageRegdateTextView.setTextColor(getResources().getColor(R.color.softYellow));
		}
		
		noticeMessageTextView.setText(LovetoConstant.systemMessageMap.get(messageType) );
		noticeMessageRegdateTextView.setText(regdate);
		tournamentIDTextView.setText(tournamentid);
		RelativeLayout clickArea = (RelativeLayout)messageNoticeLayout.findViewById(R.id.click_area);
		clickArea.setOnClickListener(this);
		return messageNoticeLayout;
	}

}
